package com.feifan.monthhelper.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.feifan.monthhelper.R;
import com.feifan.monthhelper.bean.LoveChatData;
import com.feifan.monthhelper.bean.db.DayRecordBean;
import com.feifan.monthhelper.constant.Constant;
import com.feifan.monthhelper.ui.base.BaseActivity;
import com.feifan.monthhelper.utils.DateUtils;
import com.feifan.monthhelper.wedget.view.CirclePieView;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class LoveStatisticsActivity extends BaseActivity {

    @BindView(R.id.rl_title)
    View rlTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_all_record)
    TextView tvAllRecord;
    @BindView(R.id.tv_total_love_num)
    TextView tvTotalLoveNum;
    @BindView(R.id.tv_total_protect_love_num)
    TextView tvTotalProtectLoveNum;
    @BindView(R.id.tv_total_unprotect_love_num)
    TextView tvTotalUnprotectLoveNum;
    @BindView(R.id.tv_ovulation_love_num)
    TextView tvOvulationLoveNum;
    @BindView(R.id.tv_ovulation_protect_love_num)
    TextView tvOvulationProtectLoveNum;
    @BindView(R.id.tv_ovulation_unprotect_love_num)
    TextView tvOvulationUnprotectLoveNum;
    @BindView(R.id.cpv_love_percent)
    CirclePieView cpvLovePercent;
    @BindView(R.id.love_chart)
    LineChart loveChart;

    private String[] xTags = new String[]  { "", "周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    private List<String> xTagList;
    //最近三十天的爱爱记录
    private ArrayList<DayRecordBean> loveRecordBeans;
    private List<LoveChatData> loveChatDataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View getTitleView() {
        return rlTitle;
    }

    @Override
    protected void initData() {
        loveRecordBeans = getIntent().getParcelableArrayListExtra(Constant.ConstantName.LAST_30_LOVES);
        xTagList = new ArrayList<>();
        xTagList.add("");
    }

    @Override
    protected void initView() {
        initLineChart(loveChart);

        loveChart.setData(new LineData());

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        tvAllRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoveStatisticsActivity.this, LoveRecordActivity.class);
                intent.putParcelableArrayListExtra(Constant.ConstantName.LAST_30_LOVES, loveRecordBeans);
                startActivity(intent);
            }
        });

        //无保护爱爱次数
        int unProtectLoves = 0;
        //易孕期爱爱次数
        int ovulatoryLoves = 0;
        //易孕期无保护爱爱次数
        int ovulatoryUnProtectLoves = 0;
        //最大怀孕概率
        int maxPregnancy = 0;

        if(loveChatDataList == null) {
            loveChatDataList = new ArrayList<>();
        }
        for(DayRecordBean recordBean:loveRecordBeans) {
            if(recordBean.protects == null) {
                continue;
            }

            LoveChatData loveChatData = new LoveChatData();
            //怀孕概率
            int pregnancy = 0;
            if (recordBean.state == Constant.MenstrualState.OVULATORY_DAY) {
                ovulatoryLoves++;
                if (recordBean.protects.contains("无措施")) {
                    ovulatoryUnProtectLoves++;
                    pregnancy = Constant.Percent.HIGH;
                } else if (pregnancy < Constant.Percent.LOW) {
                    pregnancy = Constant.Percent.LOW;
                }
            } else if (recordBean.state == Constant.MenstrualState.MENSTRUAL_DAY) {
                pregnancy = Constant.Percent.LOW;
            } else {
                if (recordBean.protects.contains("无措施")) {
                    pregnancy = Constant.Percent.MIDDLE;
                } else if (pregnancy < Constant.Percent.LOW) {
                    pregnancy = Constant.Percent.LOW;
                }
            }
            if(maxPregnancy < pregnancy) {
                maxPregnancy = pregnancy;
            }
            loveChatData.setPercent(pregnancy);
            loveChatData.setDate(DateUtils.init().dateToString(recordBean.createDate, DateUtils.DateStyle.MM_DD_EN));
            loveChatDataList.add(loveChatData);

            if(recordBean.protects.contains("无措施")) {
                unProtectLoves++;
            }
            cpvLovePercent.setArcPercent(maxPregnancy);
//            if(recordBean.state == Constant.MenstrualState.OVULATORY_DAY) {
//                ovulatoryLoves++;
//                if(recordBean.protects.contains("无措施")) {
//                    ovulatoryUnProtectLoves++;
//                }
//            }
        }
        tvTotalLoveNum.setText(loveRecordBeans.size() + "次");
        tvTotalProtectLoveNum.setText(loveRecordBeans.size() - unProtectLoves + "次");
        tvTotalUnprotectLoveNum.setText(unProtectLoves + "次");
        tvOvulationLoveNum.setText(ovulatoryLoves + "次");
        tvOvulationProtectLoveNum.setText(ovulatoryLoves - ovulatoryUnProtectLoves + "次");
        tvOvulationUnprotectLoveNum.setText(ovulatoryUnProtectLoves + "次");

        if(loveChatDataList != null) {
            List<Entry> entries = new ArrayList<>();
            for(int i=0;i<loveChatDataList.size();i++) {
                LoveChatData chatData = loveChatDataList.get(i);
                Entry entry = new Entry((i+1) * 10, chatData.getPercent());
                entries.add(entry);
                xTagList.add(chatData.getDate());
            }
            int tagSize = xTagList.size();
            if(tagSize < 8) {
                for(int i=0;i<8-tagSize;i++) {
                    xTagList.add("");
                }
            }
            xTags = new String[xTagList.size()];
            xTagList.toArray(xTags);
            LineDataSet dataSet = new LineDataSet(entries, "");
            LineData lineData = loveChart.getLineData();
            lineData.addDataSet(dataSet);
            loveChart.setData(lineData);
            loveChart.invalidate();
        }
    }

    private void initLineChart(LineChart loveChart) {
        loveChart.setLogEnabled(true);//打印日志
        //取消描述文字
        loveChart.getDescription().setEnabled(false);
        loveChart.setNoDataText("没有数据");//没有数据时显示的文字
        loveChart.setNoDataTextColor(Color.BLACK);//没有数据时显示文字的颜色
        loveChart.setDrawGridBackground(false);//chart 绘图区后面的背景矩形将绘制
        loveChart.setDrawBorders(false);//是否禁止绘制图表边框的线
        loveChart.setBorderColor(Color.GRAY); //设置 chart 边框线的颜色。
        loveChart.setBorderWidth(3f); //设置 chart 边界线的宽度，单位 dp。
        loveChart.setTouchEnabled(true);     //能否点击
        loveChart.setDragEnabled(false);   //能否拖拽
        loveChart.setScaleEnabled(false);  //能否缩放
        loveChart.animateX(1000);//绘制动画 从左到右
        loveChart.setDoubleTapToZoomEnabled(false);//设置是否可以通过双击屏幕放大图表。默认是true
        loveChart.setHighlightPerDragEnabled(false);//能否拖拽高亮线(数据点与坐标的提示线)，默认是true
        loveChart.setDragDecelerationEnabled(false);//拖拽滚动时，手放开是否会持续滚动，默认是true（false是拖到哪是哪，true拖拽之后还会有缓冲）

        XAxis xAxis = loveChart.getXAxis();
        xAxis.setEnabled(true);
        xAxis.setDrawGridLines(true);
        xAxis.setLabelCount(7);
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
        xAxis.enableGridDashedLine(10f, 10f, 0f);

        xAxis.setAxisMinimum(0f);
        xAxis.setAxisMaximum(70f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                System.out.println("value = " + value);
                return xTags[(int) value /10];
            }
        });

        YAxis yAxis = loveChart.getAxisLeft();
        yAxis.setEnabled(true);
        yAxis.setDrawLabels(true);

        // horizontal grid lines
        yAxis.enableGridDashedLine(10f, 20f, 0f);
        yAxis.setLabelCount(5);

        yAxis.setAxisMinimum(0f);
        yAxis.setAxisMaximum(100f);
    }

    @Override
    protected int setContentLayout() {
        return R.layout.activity_love_statistics;
    }
}
